import 'package:flutter/material.dart';

import 'package:flutter_note/note/base.dart';
import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/page_note_add.dart';
import 'package:flutter_note/note/page_note_detail.dart';
import 'package:flutter_note/note/utils.dart';
import 'package:flutter_note/note/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BookNotePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BookNotePageState();
  }
}

class _BookNotePageState extends BaseState<BookNotePage> {
  List<ReplyNote> _noteList = BookNoteManager.getInstance().getNoteList();
  BookNoteManager _bookNoteManager = BookNoteManager.getInstance();
  RefreshController _refreshController = RefreshController();
  bool _enablePullUp = true;
  bool _enablePullDown = true;

  @override
  void initState() {
    super.initState();
    _initData();
  }

  void _initData() async {
    //如果列表是空的,先从服务器拉取,如果有内容直接显示
    if (EmptyUtils.isEmpty(_noteList)) {
      await _bookNoteManager.loadData(); //必须要await,不然拉取了不能更新
    }
    _noteList = _bookNoteManager.getNoteList();
    if (EmptyUtils.isNotEmpty(_noteList) &&
        _noteList.length < Const.PAGE_SIZE) {
      _enablePullUp = false;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      appBar: AppBar(
        title: Text('${_bookNoteManager.getCurrentBook().title}'),
        elevation: dim.x2,
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              _goNoteAddPage();
            },
            child: Container(
                color: Colors.transparent,
                width: dim.x60,
                child: Icon(Icons.border_color)),
          )
        ],
      ),
      body: _body(),
    );
  }

  Widget _body() {
    if (EmptyUtils.isEmpty(_noteList)) {
      return Center(
        child: Text(
          '没有日记',
          style: TextStyle(color: color.txt3, fontSize: dim.t16),
        ),
      );
    } else {
      return SmartRefresher(
        controller: _refreshController,
        enablePullDown: _enablePullDown,
        enablePullUp: _enablePullUp,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          //列表控件
            itemCount: _noteList.length,
            itemBuilder: (BuildContext context, int position) {
              return _buildItem(_noteList[position]);
            }),
      );
    }
  }

  //ListView的Item
  Widget _buildItem(ReplyNote note) {
    return NoteView(
      note,
          () {
        if (NoteManager.getInstance().getCurrentNote() != note) {
          NoteManager.getInstance().setCurrentNote(note); //和之前的bid不一样的时候需要重新赋值
          CommentManager.getInstance().getCommentList().clear();
        }
        startPage(NoteDetailPage());
      },
    );
  }

  _goNoteAddPage() async {
    var reply = await startPageForResult(NoteAddPage());
    if (reply is Reply) {
      showMessage(reply.msg);
      await _bookNoteManager.loadData(); //必须要await,不然拉取了不能更新
      setState(() {
        _noteList = _bookNoteManager.getNoteList();
      });
    }
  }

  void _onRefresh() async {
    Reply reply = await _bookNoteManager.loadData(); //必须要await,不然拉取了不能更新
    if (reply.code != Const.SUCCESS) {
      showMessage(reply.msg);
      _refreshController.refreshCompleted();
      //_refreshController.scrollTo(_refreshController.scrollController.offset + dim.x50);
      setState(() {});
    } else {
      Future.delayed(Duration(milliseconds: 500)).then((val) {
        _refreshController.refreshCompleted();
        //_refreshController.scrollTo(_refreshController.scrollController.offset + dim.x50);
        if (EmptyUtils.isNotEmpty(_noteList) &&
            _noteList.length < Const.PAGE_SIZE) {
          _enablePullDown = false;
        }
        setState(() {});
      });
    }
  }

  void _onLoading() async {
    if (EmptyUtils.isEmpty(_noteList)) {
      _refreshController.loadComplete();
      //_refreshController.scrollTo(_refreshController.scrollController.offset + dim.x50);
      setState(() {});
      return;
    }
    Reply reply = await _bookNoteManager.loadMoreData(); //必须要await,不然拉取了不能更新
    if (reply.code == Const.FAIL) {
      _refreshController.loadFailed();
      setState(() {});
    } else if (reply.code != Const.SUCCESS) {
      showMessage(reply.msg);
      setState(() {});
    } else {
      Future.delayed(Duration(milliseconds: 2000)).then((val) {
        _refreshController.loadComplete();
        //_refreshController.scrollTo(_refreshController.scrollController.offset + dim.x50);
        setState(() {});
      });
    }
  }
}
